/**
 * 
 */
package com.moyq5.mvcmaker.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.moyq5.mvcmaker.WebModule;
import com.moyq5.mvcmaker.freemarker.FreeMarkerFactory;

import freemarker.core.ParseException;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateNotFoundException;


/**
 * （Json注解代理类的）注册类生成器
 * @author Moyq5
 * @date 2016年9月27日
 */
public class JacksonMixInFactoryMvcMaker {

	private static Logger log = LoggerFactory.getLogger(JacksonMixInFactoryMvcMaker.class);
	
	/* 生成的文件名后缀 */
	private static final String SUFFIX = "MixInFactory.java";
	/* 模板文件名 */
	private static final String FTL = "mixInFactory.ftl";
	
	private WebModule module;
	public JacksonMixInFactoryMvcMaker(WebModule module) {
		this.module = module;
	}

	@SuppressWarnings("unchecked")
	public void execute(List<String> entityNames) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException, TemplateException {
		
		String filePath = module.getPath() + File.separator + (module.getJacksonPackage().replace(".", File.separator));
		File destFile = new File(filePath, SUFFIX);

		log.debug("{}（Json注解代理类的）注册类：{}.{}", 
				new Object[]{destFile.exists() ? "更新": "创建", module.getJacksonPackage(), SUFFIX});
		
		Map<Class<?>, Class<?>> mixIns = new HashMap<Class<?>, Class<?>>();
		try {
			if (destFile.exists()) {
				Class<?> clazz = Class.forName(module.getJacksonPackage() + ".MixInFactory");
				Object mixInFactory = clazz.newInstance();
				Method method = clazz.getMethod("getMixIns");
				mixIns = (Map<Class<?>, Class<?>>)method.invoke(mixInFactory);
			} else {
				destFile.getParentFile().mkdirs();
			}
			for (String entityName : entityNames) {
				Class<?> entityClass = Class.forName(module.project().beanModule().getEntityPackage() + "." + entityName);
				if (!mixIns.containsKey(entityClass)) {
					mixIns.put(entityClass, Class.forName(module.getJacksonMixinPackage() + "." + entityName + "MixIn"));
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		FileWriter fw = new FileWriter(destFile);
		Template temp = FreeMarkerFactory.getCfg().getTemplate(FTL);
		
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("module", module); 				// 配置信息
		model.put("mixIns", mixIns);
		
		temp.process(model, fw);
		
	}
	

}
